package io.renren.modules.sqlapi;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 拼接sql的工具类
 * */
public class SqlUtil {

    //正则表达式
    private static String regex = "if:\\w+\\[[^\\]]*\\]";

    public static void main(String[] args) {
        System.out.println();
        String sql ="select a from b where if:name[ b.name =#{name} ]";
        Map param = new HashMap();
        param.put("name","a");
        System.out.println(ifSql(sql,param));

    }
    /**
     * 根据参数，判断拼接sql中的语句
     * */
    public static String ifSql(String s , Map<String,Object> params){
        //  1、模式对象：将给定的正则表达式编译成一个模式
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        //	2、匹配对象：创建匹配器，将给定的输入与模式进行匹配
        Matcher matcher = pattern.matcher(s);
        StringBuffer sb = new StringBuffer();
        int end  =0;
        while(matcher.find()){
            int searchStart = matcher.start();
            int searchEnd = matcher.end();
            if(end != searchStart){
                sb.append(s.substring(end,searchStart));
            }
            end =searchEnd;
            String searchStr = matcher.group();
            int contentStart = searchStr.indexOf("[");
            int contentEnd = searchStr.indexOf("]");
            String name = searchStr.substring(3,contentStart);
            Object value= params.get(name);
            if(value == null || "".equals(value) ){
                continue;
            }
            String str =searchStr.substring(contentStart+1,contentEnd);
            sb.append(str);
        }
        if(end != s.length()-1 ){
            sb.append(s.substring(end,s.length()));
        }
        return sb.toString();
    }

    public static String isStatic(){
        return null;
    }
}
